class Select2{ 
    constructor(element, options = {}) {
        this.originalSelect = element;
        this.options = Object.assign({
            placeholder: '请选择...',
            treeData: []
        }, options);
        this.init();
    }
    init() {
        const dv =  this.#elementInput()
        dv.appendChild(this.#elementDrown())
        this.originalSelect.appendChild(dv)
        this.#selected()
        
        
    }

    // 构建select 框
    #elementInput() {
        const dv = document.createElement('div')
        dv.className = 'select'
        // dv.onmouseleave = function() {
        //     !this.querySelector('.tree').classList.value.includes('hidden')&&this.querySelector('.tree').classList.add('hidden')
        // } 
        const div = document.createElement('div')
        div.className = 'sel'
        div.onclick = function (){
            this.nextElementSibling.classList.toggle('hidden')
        } 
        const dvL = document.createElement('div')
        dvL.innerHTML = this.options.placeholder
        const dvR = document.createElement('div')
        dvR.innerText = '^'
        div.appendChild(dvL)
        div.appendChild(dvR)
        dv.appendChild(div)
        return dv
    }
    // 下拉
    #elementDrown() {
        const ul = document.createElement('ul')
        ul.id = 'tree'
        ul.className = 'tree hidden'
        this.options = {...this.options, treeElement: ul}
        return this.#renderTree(this.options)
    }
    #renderTree(obj) {
        let that = this
        obj.treeData.forEach(node => {
            // 创建节点元素
            const li = document.createElement('li');
            li.className = 'tree-node';
            if (!node.children || node.children.length === 0) {
                li.classList.add('leaf');
            } else {
                li.classList.add('root');
                li.classList.add('collapsed');
            }
    
            // 创建节点内容
            const nodeContent = document.createElement('div');
            nodeContent.className = 'tree-node-content';
            nodeContent.dataset.id = node.id;
            
            // 创建展开/折叠图标
            const icon = document.createElement('span');
            icon.className = 'tree-node-icon';
            icon.innerHTML = '▶';
    
            icon.onclick = function() {
                let node = this.closest('.tree-node')
                if (node.classList.contains('leaf')) return;
    
                if (node.classList.contains('expanded')) {
                    node.classList.remove('expanded');
                    node.classList.add('collapsed');
                } else {
                    node.classList.remove('collapsed');
                    node.classList.add('expanded');
                }
            }
            nodeContent.appendChild(icon);
            // checkbox
            const checkbox = document.createElement('div');
            checkbox.className = 'checkbox';
            
            if(this.options.selectVal.includes(node.id)) {
                checkbox.className = 'checkbox checkbox-completed'
            }


            // 将当前数据存储到节点上
            checkbox.data = node
            if (!node.children || node.children.length === 0) {
                checkbox.expand = 'check-leaf';
            } else {
                checkbox.expand = 'check-root';
            }
    
            checkbox.onclick = function() {
                if(this.className == 'checkbox') {
                    this.className = 'checkbox checkbox-completed'
                }else {
                    this.className = 'checkbox'
                }
                // 选中所有子集
                this.closest('li').querySelectorAll('.checkbox').forEach(el=> {
                    el.className = this.classList
                })
                obj.onSelected&& obj.onSelected(this)
                that.#parentUpdateEle(this.closest('.root'))
            }

            nodeContent.appendChild(checkbox);
    
            // 创建节点标题
            const title = document.createElement('span');
            title.className = 'tree-node-title';
            title.textContent = node.title;
            nodeContent.appendChild(title);
    
            li.appendChild(nodeContent);
    
            // 如果有子节点，递归渲染
            if (node.children && node.children.length > 0) {
                const ul = document.createElement('ul');
                ul.className = 'tree-children';
                li.appendChild(ul);
                // 递归渲染子节点
                this.#renderTree({...obj, treeData: node.children, treeElement:ul});
            }
            obj.treeElement.appendChild(li);
        });
        return obj.treeElement
    }
    #parentUpdateEle(node) {
        if(!node) return
        let checkArr = []
        node.querySelectorAll('.checkbox').forEach((el, index)=> {
            if(index == 0) return
            checkArr.push(el.classList.value.includes('checkbox-completed'))
        })
        const obj = node.querySelector('.checkbox')
        if(checkArr.every(item=>item==true))  {
            obj.className  = 'checkbox checkbox-completed'
        } else if(checkArr.some(item=>item==true))  {
            obj.className  = 'checkbox checkbox-pendding'
        }else {
            obj.className  = 'checkbox'
        }
        if(node.parentElement.closest('.root')) {
            this.#parentUpdateEle(node.parentElement.closest('.root'))
        }
    }
    // 选中父级
    #selected() {
        this.originalSelect.querySelectorAll('.checkbox-completed').forEach(item=>{
            let arr = []
            item.parentElement.closest('.root').querySelectorAll('.checkbox').forEach((ie,index)=>{
                if(index == 0) return
                arr.push(ie.className.includes('checkbox-completed'))
            })
            if(arr.every(e=>e==true))  {
                item.parentElement.closest('.root').querySelector('.checkbox').classList.add('checkbox-completed')
            }else if(arr.some(e=>e==true)) {
                let arr2 = []
                item.parentElement.closest('.root').querySelectorAll('.checkbox').forEach((el, i)=> {
                    if(i == 0) return
                    if(!el.parentElement.parentElement.className.includes('root')) {
                        arr2.push(el.className.includes('checkbox-completed'))
                    }
                })
                if(arr2.every(e=>e==true))  {
                    item.parentElement.closest('.root').querySelector('.checkbox').classList.add('checkbox-completed')
                }else if(arr2.some(e=>e==true)) {
                    item.parentElement.closest('.root').querySelector('.checkbox').classList.add('checkbox-pendding')
                }
            }
        })
    }
}

// 默认CSS样式
const style = document.createElement('style');
style.textContent = `
.tree {
    height: 200px;
    overflow: auto;
    border: 1px solid #f0f0f0;
    list-style-type: none;
    position: absolute;
    z-index: 100;
    background-color: #fff;
    width: 100%;
}

/* 树形样式 */
.tree-container {
    margin: 20px 0;
    border: 1px solid #f0f0f0;
    border-radius: 2px;
    padding: 15px;
}
.tree-node {
    padding: 4px 0;
}
.tree-children {
    list-style-type: none;
    padding-left: 20px;
    overflow: hidden;
    transition: all 0.3s;
}
.tree-node-content {
    display: flex;
    align-items: center;
    cursor: pointer;
    border-radius: 2px;
    padding: 3px 5px;
}
.tree-node-content:hover {
    background-color: #f5f5f5;
}
.tree-node-content.selected {
    background-color: #e6f7ff;
}
.tree-node-icon {
    width: 16px;
    height: 16px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-right: 5px;
    font-size: 12px;
    transition: transform 0.3s;
}
.tree-node-title {
    flex: 1;
}
.expanded .tree-node-icon {
    transform: rotate(90deg);
}
.collapsed .tree-node-icon {
    transform: rotate(0deg);
}
.collapsed .tree-children {
    display: none;
}
.leaf .tree-node-icon {
    visibility: hidden;
}

/* 控制区域样式 */
.controls {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f9f9f9;
    border-radius: 2px;
}

.select {
    border: 1px solid #f0f0f0;
    position: relative;
}
.checkbox {
    height: 20px;
    width: 20px;
    border: 1px solid;
    border-radius: 3px;
    display: inline-block;
    position: relative;
}

.checkbox-pendding::after {
    content: ' ';
    display: inline-block;
    padding:30%;
    background-color: blue;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

}
/* 模拟checkbox选中状态 */
.checkbox-completed::after {
    content: '✔';
    height: 100%;
    width: 100%;
    display: inline-block;
    background-color: blue;
    color: #fff;
    position: absolute;
    text-align: center;
}
.sel {
    display: flex;
    justify-content: space-between;
}
.hidden {
    display: none;
}
`;
document.head.appendChild(style);
document.onclick = function(e) {
    if (e.target.closest('.select')) {
        return; // 如果是则直接返回，不执行后续代码
    }
    document.getElementById('tree').classList.add('hidden')
}
